<script lang="ts">
import {defineComponent, onMounted, reactive, ref, toRefs} from 'vue'
import UserUI from "@/views/system/user/ui/view/useUI.vue";
import PageTable from "@/components/pageTable/pageTable.vue";
import {QueryParamConfig, TableListConfig} from "@/components/pageTable/types/type.ts";
import SaveForm from "@/components/saveForm/saveForm.vue";
import { SaveFormConfig} from "@/components/saveForm/types/type.ts";
import {MOBILE_REG} from "@/common/comConstant/commoncanstant.ts";
import {axiosHttp} from "@/util/axios.ts";
import type {Result} from "@/common/comTypes/commonTypes.ts";
import {sendGlobalMessage} from "@/hooks/globalmessage.ts";

export default defineComponent({
  name: 'user',
  components: {SaveForm, PageTable, UserUI},

  setup() {

    onMounted(() => {
      data.VITE_UI_MODE = JSON.parse(import.meta.env.VITE_UI_MODE) || false
      console.log(data.VITE_UI_MODE)
    })
    const data = reactive({
      VITE_UI_MODE: false,
      queryParam: {
        username: "",
        mobile: "",
        nickname: "",
        status: ""
      },
      queryConfigList: <QueryParamConfig[]>[
        new QueryParamConfig().buildLabel("账号").buildProp("username"),
        new QueryParamConfig().buildLabel("手机号").buildProp("mobile"),
        new QueryParamConfig().buildLabel("昵称").buildProp("nickname"),
        new QueryParamConfig().buildLabel("状态").buildProp("birthday").buildCustomSlotName("queryStatusSlot"),
      ],
      tableConfigList: <TableListConfig[]>[
        new TableListConfig().buildLabel("账号").buildProp("username"),
        new TableListConfig().buildLabel("昵称").buildProp("nickname"),
        new TableListConfig().buildLabel("手机号").buildProp("mobile"),
        new TableListConfig().buildLabel("创建时间").buildProp("createDate"),
        new TableListConfig().buildLabel("最近更新时间").buildProp("updateDate"),
        new TableListConfig().buildLabel("邮箱").buildProp("email"),
        new TableListConfig().buildLabel("出生日期").buildProp("birthday"),
        new TableListConfig().buildLabel("状态").buildProp("status").buildCustomSlotName("tableStatusSlot"),
        new TableListConfig().buildLabel("微信OPEN_ID").buildProp("openId"),
        new TableListConfig().buildLabel("操做").buildCustomSlotName("tableOperateSlot"),
      ],
      listUrl: "/user/list",
      statusList: [
        {
          label: "禁用",
          value: 0
        },
        {
          label: "正常",
          value: 1
        }
      ],
      saveFormConfigList: <SaveFormConfig[]>[
        new SaveFormConfig().buildLabel("用户名").buildProp("username").buildGroup(["detail"]).buildPlaceholder("无需填写,使用手机号作为用户名"),
        new SaveFormConfig().buildLabel("手机号").buildProp("mobile").buildGroup(['add', 'detail']),
        new SaveFormConfig().buildLabel("昵称").buildProp("nickname").buildPlaceholder("默认昵称为:用户+手机号后四位"),
        new SaveFormConfig().buildLabel("邮箱").buildProp("email").buildGroup(["detail"]),
        new SaveFormConfig().buildLabel("微信openId").buildProp("openId").buildGroup(["detail"]),
        new SaveFormConfig().buildLabel("创建时间").buildProp("createDate").buildGroup(["detail"]),

      ],
      saveForm: {
        mobile: "",
        nickname: ""
      },
      title: "新增用户",
      currentGroup: 'add',
      detailUrl: "/user/detail",
      saveUrl: "/user/save",
    })

    const methods = {
      init() {
        refs.pageTableRef.value.init()
      },
      save(id: string, detail: boolean = false) {
        if (detail) {
          data.title = "用户详情"
          data.currentGroup = 'detail'
        } else {
          data.title = id ? '编辑用户' : '新增用户'
          data.currentGroup = id ? 'update' : 'add'
        }

        refs.saveFormRef.value.init(id)
      },
      async nicknameExist(nickname: string): Promise<Result<boolean>> {
        return await axiosHttp.get("/user/nicknameExist/" + nickname)
      },
      async mobileExits(mobile: string): Promise<Result<boolean>> {
        return await axiosHttp.get("/user/mobileExist/" + mobile)
      },
      saveSuccess() {
        sendGlobalMessage("保存成功")
        methods.init()
      },
      //关闭之前处理
      beforeClose() {
        data.saveForm = {
          mobile: "",
          nickname: ""
        }
      },
      updateForm(form: any) {
        data.saveForm = form || {}
      },
      async updateStatus(user: any) {
        let res = await axiosHttp.post("/user/updateStatus", {
          id: user?.id,
          status: user?.status == 0 ? 1 : 0
        })
        if (res.isSuccess()) {
          methods.init()
          sendGlobalMessage("操作成功")
        }
      }
    }

    const validators = {
      async validateMobile(rule: any, value: string, callback: Function) {
        if (data.currentGroup == 'add') {
          if (!value) {
            callback(new Error('请输入手机号'));
          } else if (!MOBILE_REG.test(value)) {
            callback(new Error('手机号格式不正确'));
          } else {
            let mobleExits = await methods.mobileExits(value)
            if (mobleExits.isSuccess()) {
              if (mobleExits?.data) {
                callback("该手机号已注册,请确认输入手机号是否无误")
              }
            }
            callback();
          }
        }
      },
      async validateNickname(rule: any, value: string, callback: Function) {
        if (value) {
          //不等于空 去查询数据库看是否已经有该昵称
          let exist = await methods.nicknameExist(value)
          if (exist.isSuccess()) {
            if (exist.data) {
              callback("该昵称已经存在,请重新输入!")
            }
          }
        }
        callback()
      }
    }


    const rules = reactive({
      saveFormRules: {
        mobile: [
          {required: true, validator: validators.validateMobile, trigger: 'blur'}
        ],
        nickname: [
          {
            required: false, validator: validators.validateNickname, trigger: "blur"
          }
        ]
      }
    })

    const refs = {
      saveFormRef: ref(),
      pageTableRef: ref()
    }


    return {
      ...toRefs(data),
      ...methods,
      ...validators,
      ...rules,
      ...refs
    }
  }
})
</script>

<template>
  <div>
    <!--   仅展示ui -->
    <user-u-i v-if="VITE_UI_MODE"></user-u-i>
    <div v-if="!VITE_UI_MODE">
      <page-table
          ref="pageTableRef"
          :query-param="queryParam"
          :query-config-list="queryConfigList"
          :table-config-list="tableConfigList"
          :list-url="listUrl"
          :row-number="4"
          :open-selection="false"
          @handler-add="save"
      >
        <template #queryStatusSlot>
          <el-select v-model="queryParam.status" placeholder="请选择状态">
            <el-option v-for="(item,index) in statusList" :key="index" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </template>
        <template #tableStatusSlot="{row,index}">
          {{ statusList.find(e => e.value == row.status)?.label || "-" }}
        </template>

        <template #tableOperateSlot="{row,index}">
          <el-button type="text" :disabled="row.username=='admin'" title="admin账号不能修改" @click="save(row?.id)">
            编辑
          </el-button>
          <el-button type="text" @click="save(row?.id,true)">详情</el-button>
          <el-popconfirm
              confirm-button-text="确认"
              cancel-button-text="取消"
              icon="WarningFilled"
              icon-color="#e64646"
              :title="'确定要'+(row.status==1?'禁用':'解禁')+'用户'+row.nickname+'?'"
              @confirm="updateStatus(row)"
              @cancel="()=>{}"
          >
            <template #reference>
              <el-button type="text">{{ row.status == 1 ? '禁用' : '解禁' }}</el-button>
            </template>
          </el-popconfirm>

        </template>
      </page-table>

      <save-form ref="saveFormRef"
                 :save-form-config-list="saveFormConfigList"
                 :save-form="saveForm"
                 :rules="saveFormRules"
                 :detail-url="detailUrl"
                 :save-url="saveUrl"
                 :current-group="currentGroup"
                 :title="title"
                 @save-success="saveSuccess"
                 @before-close="beforeClose"
                 @update-form="updateForm"

      ></save-form>
    </div>
  </div>

</template>

<style scoped>

</style>